package fiuba.dao.hibernate;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Transient;

import fiuba.dao.MenuItemDao;
import fiuba.model.LabelValue;
import fiuba.model.MenuItem;
import fiuba.model.Role;


public class MenuItemDaoHibernate extends GenericDaoHibernate<MenuItem, Long> implements MenuItemDao {

	public MenuItemDaoHibernate(){
		super(MenuItem.class);
	}
	
	public MenuItem getMenuItemByName(String menuItemName) {
		   List menuItems = getHibernateTemplate().find("from MenuItem where name=?", menuItemName);
	        if (menuItems.isEmpty()) {
	            return null;
	        } else {
	            return (MenuItem) menuItems.get(0);
	        }
	}

	public void remove(Long id) {
		this.remove(id);
	}

    public MenuItem save(MenuItem object) {		
		return this.saveMenuItem(object);
	}
    @SuppressWarnings("unchecked")
	public List<MenuItem> getMenuItems() {
    	log.debug("menuItemDaoHibernate");
		return getHibernateTemplate().find("from MenuItem m order by upper(m.name)");
	}    
    

	public MenuItem saveMenuItem(MenuItem menuItem) {
		  log.debug("menu's id: " + menuItem.getId());
		  menuItem = super.save(menuItem);
		  //getHibernateTemplate().saveOrUpdate(menuItem);
	        // necessary to throw a DataIntegrityViolation and catch it in MenuManager
	        getHibernateTemplate().flush();
	        
	        return menuItem;
	}

	public List<LabelValue> getItemList() {
	    List<LabelValue> menuItems = new ArrayList<LabelValue>();
	    for (MenuItem item : this.getMenuItems()) {
	        // convert the user's roles to LabelValue Objects
	        menuItems.add(new LabelValue(item.getName(), item.getId().toString()));
	    }
	    return menuItems;
	}

}
